<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>

<s:include value="/WEB-INF/content/common/header.jsp" />
<title><s:text name="global.application.title" /> - <s:text name="global.title.weekdata" /></title>
<link href="<s:url value='/theme/css/idangerous.swiper.css' />" rel="stylesheet" />
<link href="<s:url value='/theme/css/swipepage.css' />" rel="stylesheet" />

<script type="text/javascript">
	$(document).ready(function() {

		var bph = [];
		var bpl = [];
		var pr = [];
		var bt = [];
		var dmy = [];
		var week = [];
		
		function generateChartData() {
			<s:iterator value="weekDaysEn">
				var endate = '< s:property />';		
				var md = endate.split("/");
				var weekdate = new Date(parseInt(md[0])+2000,parseInt(md[1])-1,parseInt(md[2]));
				week.push(weekdate);
			</s:iterator>
			
			jQuery('.data-row').each(function() {

				var regDate = new Date(jQuery(this).find('.dataregDate').val());
				var bloodPH = null;
				var	bloodPL = null;
				var	pulseR = null;
				var	bloodT = null;
				
				bloodPH = jQuery(this).find('.databph').val();
				bloodPL = jQuery(this).find('.databpl').val();
				pulseR = jQuery(this).find('.datapr').val();
				bloodT = jQuery(this).find('.databt').val();
				
				bph.push([ regDate, bloodPH ]);
				bpl.push([ regDate, bloodPL ]);
				pr.push([ regDate, pulseR ]);
				bt.push([ regDate, bloodT ]);
				dmy.push([ regDate, 0 ]);
				
			});

			for(var count=0;count<7;count++){
			
				wd = new Date(week[count]);
				
				bph.push([ wd, null ]);
				bpl.push([ wd, null ]);
				pr.push([ wd, null ]);
				bt.push([ wd, null ]);
				dmy.push([ wd, 0 ]);
			}
		}

		generateChartData();
		
		var miny = 200;
		var maxy = 0;
		
		var miny2 = 70;
		var maxy2 = 0;
		
		function setMinMax(){
		
			for(var en=0;en<bph.length;en++){
				var entry = parseInt(bph[en][1]);
				if(entry!=null){
					if(miny>entry){miny=entry;}
					if(maxy<entry){maxy=entry;}
				}
			}
			
			for(var en=0;en<bpl.length;en++){
				var entry = parseInt(bpl[en][1]);
				if(entry!=null){
					if(miny>entry){miny=entry;}
					if(maxy<entry){maxy=entry;}
				}
			}
			
			for(var en=0;en<pr.length;en++){
				var entry = parseInt(pr[en][1]);
				if(entry!=null){
					if(miny>entry){miny=entry;}
					if(maxy<entry){maxy=entry;}
				}
			}
			
			for(var en=0;en<bt.length;en++){
				var entry = parseFloat(bt[en][1]);
				if(entry!=null){
					if(miny2>entry){miny2=entry;}
					if(maxy2<entry){maxy2=entry;}
				}
			}
		}
		setMinMax();
		
		plot1 = $.jqplot("chartdiv",[ bph, bpl, pr, bt, dmy ],{

			animate : true,

			animateReplot : false,
			cursor : {
				show : true,
				zoom : true,
				looseZoom : false,
				showTooltip : false
			},
			seriesColors : [ "#FF3300", "#FFFF00", "#33CC33", "#0066FF" ],
			seriesDefaults : {

				renderer : $.jqplot.LineRenderer,
				rendererOptions : {},
				markerRenderer : $.jqplot.MarkerRenderer,
			},

			series : [
					{
						yaxis : 'yaxis',
						label : '<s:text name="WeekData.BPH" />',
						markerOptions : {
							show : true,
							style : 'filledDiamond ',
						}
					},
					{
						yaxis : 'yaxis',
						label : '<s:text name="WeekData.BPL" />',
						markerOptions : {
							show : true,
							style : 'filledDiamond ',
						}
					},
					{
						yaxis : 'yaxis',
						label : '<s:text name="WeekData.PR" />',
						markerOptions : {
							show : true,
							style : 'filledSquare',
						}
					},
					{
						yaxis : 'y2axis',
						label : '<s:text name="WeekData.BT" />',
						markerOptions : {
							show : true,
							style : 'filledCircle',
						}
					},
					{
						yaxis : 'yaxis',
						markerOptions : {
							show : false
						},
						showLabel: false
					} ],
			title : {
				text : '<s:text name="WeekData.Chart.Title" />',
				show : true,
			},
			axesDefaults : {
				showTicks : true,
				showTickMarks : true,
				pad : 0
			},
			grid : {
				backgroundColor : 'white'
			},
			gridPadding : {
				top : null,
				bottom : 40,
				left : 50,
				right : null
			},

			axes : {
				xaxis : {
					renderer : $.jqplot.DateAxisRenderer,
					rendererOptions : {
						tickInset : 0
					},
					
					label : '<s:text name="WeekData.Chart.X.Label" />',

					tickRenderer : $.jqplot.CanvasAxisTickRenderer,
					tickOptions : {
						formatString : '%b %e',
						angle : -30,
						
					},
					numberTicks : 7,
					tickInterval : 0,
				},
				yaxis : {
					tickOptions : {
						formatString : "%'d"
					},
					label : '<s:text name="WeekData.Chart.YL.Label" />',
					//show : true,
					min : miny-5,
					max : maxy+5,
					//pad : 1.2,
					rendererOptions : {
						alignTicks : true,
						forceTickAt0 : false
					}
					//autoscale:true
				},
				y2axis : {
					tickOptions : {
						formatString : "%'2.2f"
					},
					label : '<s:text name="WeekData.Chart.YR.Label" />',
					min : miny2-0.5,
					max : maxy2+0.5,
					rendererOptions : {
						alignTicks : true,
						forceTickAt0 : false
					}
					//autoscale:true
				}
			},

			legend : {
				show : true,
				location : 'ne'
			},

			highlighter : {
				show : true,
				showLabel : true,
				tooltipAxes : 'y',
				sizeAdjust : 10,
				tooltipLocation : 'ne'
			}
		});
	});
	window.onresize = function() {
		plot1.replot();
	};
	
	function alignLegend() {
		$('.jqplot-table-legend-swatch').attr("rowspan", "4");
		$('.jqplot-table-legend-label').attr("rowspan", "4");
		$('.jqplot-table-legend').attr("style",	"margin-top:20px; margin-left:50px;");
	}
</script>

<script type="text/javascript">

	function getLineheight(obj) {
		var lineheight;
		if (obj.css('line-height') == 'normal') {
			lineheight = obj.css('font-size');
		} else {
			lineheight = obj.css('line-height');
		}
		return parseInt(lineheight.replace('px', ''));
	}

	function getTextAlign(obj) {
		var textalign = obj.css('text-align');
		if (textalign == '-webkit-auto') {
			textalign = 'left';
		}
		return textalign;
	}

	function printAtWordWrap(context, text, x, y, fitWidth, lineheight) {
		var textArr = [];
		fitWidth = fitWidth || 0;

		if (fitWidth <= 0) {
			textArr.push(text);
		}

		var words = text.split(' ');
		var idx = 1;
		while (words.length > 0 && idx <= words.length) {
			var str = words.slice(0, idx).join(' ');
			var w = context.measureText(str).width;
			if (w > fitWidth) {
				if (idx == 1) {
					idx = 2;
				}
				textArr.push(words.slice(0, idx - 1).join(' '));
				words = words.splice(idx - 1);
				idx = 1;
			} else {
				idx++;
			}
		}
		if (words.length && idx > 0) {
			textArr.push(words.join(' '));
		}
		if (context.textAlign == 'center') {
			x += fitWidth / 2;
		}
		if (context.textBaseline == 'middle') {
			y -= lineheight / 2;
		} else if (context.textBaseline == 'top') {
			y -= lineheight;
		}
		for (idx = textArr.length - 1; idx >= 0; idx--) {
			var line = textArr.pop();
			if (context.measureText(line).width > fitWidth
					&& context.textAlign == 'center') {
				x -= fitWidth / 2;
				context.textAlign = 'left';
				context.fillText(line, x, y + (idx + 1) * lineheight);
				context.textAlign = 'center';
				x += fitWidth / 2;
			} else {
				context.fillText(line, x, y + (idx + 1) * lineheight);
			}
		}
	}

	function findPlotSize(obj) {
		var width = obj.width();
		var height = obj.height();
		var legend = obj.find('.jqplot-table-legend');
		if (legend.position()) {
			height = legend.position().top + legend.height();
		}
		obj.find('*').each(function() {
			var offset = $(this).offset();
			tempWidth = offset.left + $(this).width();
			tempHeight = $(this).height();
			if (tempWidth > width) {
				width = tempWidth;
			}
			if (tempHeight > height) {
				height = tempHeight;
			}
		});
		return {
			width : width,
			height : height + 30
		};
	}

	function jqplotToImg(obj) {
		var newCanvas = document.createElement("canvas");
		var size = findPlotSize(obj);
		newCanvas.width = size.width;
		newCanvas.height = size.height;

		// check for plot error
		var baseOffset = obj.offset();
		if (obj.find("canvas.jqplot-base-canvas").length) {
			baseOffset = obj.find("canvas.jqplot-base-canvas").offset();
			baseOffset.left -= parseInt(obj.css('margin-left')
					.replace('px', '') + 20);
		}

		// fix background color for pasting
		var context = newCanvas.getContext("2d");
		var backgroundColor = "rgba(255,255,255,1)";
		obj.children(':first-child').parents().each(function() {
			if ($(this).css('background-color') != 'transparent') {
				backgroundColor = $(this).css('background-color');
				return false;
			}
		});
		context.fillStyle = backgroundColor;
		context.fillRect(0, 0, newCanvas.width, newCanvas.height);

		// add main plot area
		obj.find('canvas').each(
				function() {
					var offset = $(this).offset();
					newCanvas.getContext("2d").drawImage(this,
							offset.left - baseOffset.left,
							offset.top - baseOffset.top);
				});

		obj.find(".jqplot-series-canvas > div").each(
				function() {
					var offset = $(this).offset();
					var context = newCanvas.getContext("2d");
					context.fillStyle = $(this).css('background-color');
					context.fillRect(offset.left
							- baseOffset.left
							- parseInt($(this).css('padding-left').replace(
									'px', '')), offset.top - baseOffset.top, $(
							this).width()
							+ parseInt($(this).css('padding-left').replace(
									'px', ''))
							+ parseInt($(this).css('padding-right').replace(
									'px', '')), $(this).height()
							+ parseInt($(this).css('padding-top').replace('px',
									''))
							+ parseInt($(this).css('padding-bottom').replace(
									'px', '')));
					context.font = [ $(this).css('font-style'),
							$(this).css('font-size'),
							$(this).css('font-family') ].join(' ');
					context.fillStyle = $(this).css('color');
					context.textAlign = getTextAlign($(this));
					var txt = $.trim($(this).html()).replace(/<br style="">/g,
							' ');
					var lineheight = getLineheight($(this));
					printAtWordWrap(context, txt,
							offset.left - baseOffset.left, offset.top
									- baseOffset.top
									- parseInt($(this).css('padding-top')
											.replace('px', '')), $(this)
									.width(), lineheight);
				});

		// add x-axis labels, y-axis labels, point labels
		obj.find('div.jqplot-axis > div, div.jqplot-point-label, div.jqplot-error-message, .jqplot-data-label, div.jqplot-meterGauge-tick, div.jqplot-meterGauge-label')
				.each(function() {
					var offset = $(this).offset();
					var context = newCanvas.getContext("2d");
					context.font = [ $(this).css('font-style'),
							$(this).css('font-size'),
							$(this).css('font-family') ].join(' ');
					context.fillStyle = $(this).css('color');
					var txt = $.trim($(this).text());
					var lineheight = getLineheight($(this));
					printAtWordWrap(context, txt, offset.left
							- baseOffset.left, offset.top
							- baseOffset.top - 2.5, $(this).width(),
							lineheight);
				});

		// add the title
		obj.children("div.jqplot-title").each(
				function() {
					var offset = $(this).offset();
					var context = newCanvas.getContext("2d");
					context.font = [ $(this).css('font-style'),
							$(this).css('font-size'),
							$(this).css('font-family') ].join(' ');
					context.textAlign = getTextAlign($(this));
					context.fillStyle = $(this).css('color');
					var txt = $.trim($(this).text());
					var lineheight = getLineheight($(this));
					printAtWordWrap(context, txt,
							offset.left - baseOffset.left, offset.top
									- baseOffset.top, newCanvas.width
									- parseInt(obj.css('margin-left').replace(
											'px', ''))
									- parseInt(obj.css('margin-right').replace(
											'px', '')), lineheight);
				});

		// add the legend
		obj.children("table.jqplot-table-legend").each(
				function() {
					var offset = $(this).offset();
					var context = newCanvas.getContext("2d");
					context.strokeStyle = $(this).css('border-top-color');
					context.strokeRect(offset.left - baseOffset.left,
							offset.top - baseOffset.top, $(this).width(), $(
									this).height());
					context.fillStyle = $(this).css('background-color');
					context
							.fillRect(offset.left - baseOffset.left, offset.top
									- baseOffset.top, $(this).width(), $(this)
									.height());
				});

		// add the swatches
		obj.find("div.jqplot-table-legend-swatch").each(
				function() {
					var offset = $(this).offset();
					var context = newCanvas.getContext("2d");
					context.fillStyle = $(this).css('border-top-color');
					context.fillRect(offset.left - baseOffset.left, offset.top
							- baseOffset.top, $(this).parent().width(), $(this)
							.parent().height());
				});

		obj.find("td.jqplot-table-legend").each(
				function() {
					var offset = $(this).offset();
					var context = newCanvas.getContext("2d");
					context.font = [ $(this).css('font-style'),
							$(this).css('font-size'),
							$(this).css('font-family') ].join(' ');
					context.fillStyle = $(this).css('color');
					context.textAlign = getTextAlign($(this));
					context.textBaseline = $(this).css('vertical-align');
					var txt = $.trim($(this).text());
					var lineheight = getLineheight($(this));
					printAtWordWrap(context, txt,
							offset.left - baseOffset.left, offset.top
									- baseOffset.top
									+ parseInt($(this).css('padding-top')
											.replace('px', '')), $(this)
									.width(), lineheight);
				});

		// then convert the image to base64 format
		return newCanvas.toDataURL("image/png");
	}

	function save(id) {
		var output = jqplotToImg($(id));
		var a = document.createElement('a');

		a.setAttribute('download', 'WeekVitalChart.png');
		a.href = output;
		a.innerHTML = 'DownloadAsImage';
		a.style.display = 'none';
		document.body.appendChild(a);
		a.click();
	}
	
	$(function() {
		$('#chartdiv').contextPopup({
			items : [ {
				label : 'Save As Image',
				icon : '../theme/img/saveicon.png',
				action : function() {
					save('#chartdiv');
				}
			} ]
		});
	});
</script>

</head>
<body>	
	<s:include value="/WEB-INF/content/common/title-head.jsp" />
	<script src="<s:url value='/theme/js/idangerous.swiper-2.0.min.js'/>" type="text/javascript" ></script>
	<script src="<s:url value='/theme/js/swipepage.js'/>" type="text/javascript" ></script>

	<div data-role="content" style="padding:0px;">
		<div class="ui-bar ui-bar-d" style="margin-top:10px; padding:10px 10px 10px 10px;" data-icon="check">
			<div class="center" >
				<h5 style="margin-top:5px;"><s:text name="WeekData.WeeklyCareRecords" /></h5>
			</div>	

			<s:form id = "weekDataForm" class="form-inline" action="view" namespace="/weekData" data-ajax="false">
				<fieldset class="ui-grid-d" style="margin-top:10px;">
				
					<div class="ui-block-a barminitext center" style="width:15%; margin-left:10px; ">
						<span><s:text name="WeekData.Selected.Week" /></span>
					</div>
					
					<div class="ui-block-b" style="width:30%; " data-mini="true">
						<input class="center" data-mini="true" id="startDate" name="weekStartDate" type="text" value ='<s:property value="weekStartDate"/>' readonly>
					</div>
					
					<div class="ui-block-c barminitext center" style="width:5%; ">
						<span>-</span>
					</div>
					
					<div class="ui-block-d" style="width:30%; ">
						<input class="center" data-mini="true" id="endDate" name="weekEndDate" type="text" value = '<s:property value="weekEndDate"/>' readonly>
					</div>
						
					<div class="ui-block-e" style="width:18%; ">
						<button data-mini="true" class="btn btn-custom" name="btnValue" value="getweek" type="submit">
							<s:text name="WeekData.Selected.Week.GetData" />
						</button>
					</div>	
									
				</fieldset>	
				
				<div class="center" data-role="controlgroup" data-type="horizontal" data-mini="true" style="margin-top:5px;">
				  <button id= "prevbtn" class="btn btn-custom" name="btnValue" value='prev' type="submit" data-iconpos="left" data-icon="arrow-l">
				  	<s:text name="WeekData.Selected.Week.PrevWeek" /></button>
				  <button id= "thisbtn" class="btn btn-custom" name="btnValue" value='this' type="submit">
				  	<s:text name="WeekData.Selected.Week.ThisWeek" /></button>
				  <button id= "nextbtn" class="btn btn-custom" name="btnValue" value='next' type="submit" data-iconpos="right" data-icon="arrow-r">
				  	<s:text name="WeekData.Selected.Week.NextWeek" /></button>
				</div>			
				
			</s:form>			
		</div>
	</div>
	
	<div data-role="content">
		<div class="chartdata">
			<table class="hidden" style="display:none;">
				<s:iterator value="chartDataRecords" status="rowIndex">
					<tr class="data-row">
						<td><input class="dataregDate"
							value="<s:date name="%{dateReg}" format="MM/dd/yyyy HH:mm"/>"></input></td>
						<td><input class="datatime"
							value="<s:date name="%{time}" format="HH:mm"/>"></input></td>
						<td><input class="databph"
							value="<s:property value="bph" />"></input></td>
						<td><input class="databpl"
							value="<s:property  value='bpl' />"></input></td>
						<td><input class="datapr" value="<s:property  value='pr' />"></input></td>
						<td><input class="databt" value="<s:property  value='bt' />"></input></td>
					</tr>
				</s:iterator>
			</table>
		</div>
		<div id="chartdiv" class="wellwhite" style="height: 300px;"></div>
	</div>
	
	<div data-role="content" style="margin-top:-40px">
	
			<div class="swiper-container swiper-nav">
				<div class="swiper-wrapper">
					<s:iterator value="weekDaysJa" status="rowIndex3">	
						<div id="tabHeader<s:property value='#rowIndex3.index'/>" class="swiper-slide" style="width:125px">
							<span class="angle"></span>
							<div class="title"><s:property/></div>
						
							<%-- <s:a href="#tab%{#rowIndex3.index}" data-toggle="tab">
								<s:property/>
							</s:a> --%>
						</div>
					</s:iterator>
				</div>
			</div>

			<div class="wellswiperdata center" id="data" >				
				<div class="swiper-pages swiper-container">
					<div class="swiper-wrapper">
						<s:iterator var="counter" begin="1" end="7" status="rowIndex">	
							<div class="swiper-slide" id="weektab<s:property value='#rowIndex.index'/>">
								<div class="inner">
								<table id="hor-minimalist-b">
									<thead>
										<tr>
											<th class="nowrap"><s:text name="#" /></th>
											<th class="nowrap"><s:text name="WeekData.Time" /></th>
											<th class="nowrap"><s:text name="WeekData.ActionItem" /></th>
											<th class="nowrap"><s:text name="WeekData.Answer" /></th>
										</tr>
									</thead>
									<s:set name="itrVar" value='1'/>
									<s:iterator value="weekDataRecords" status="rowIndex2">
										<tr>
											 <s:if test="uid == #rowIndex.index + 1">
												<td><s:property value='#itrVar' /></td>
												<td><s:date name="%{actionTimeFrom}" format="hh:mm a"/></td>
												<td><s:property value="actionItem" /></td>
												<td><s:property value="answer" /></td>
												<s:set name="itrVar" value="#itrVar + 1"/>
											 </s:if>
										</tr>
									</s:iterator>	
								</table>
							</div>
						</div>
					</s:iterator>
				</div>
			</div>
		</div>
	</div>
	
	<script type="text/javascript">
	
	 	var currentWeekDay = <s:property value="currentWeekDay"/>;	
	 	if(currentWeekDay != "-1"){
			$("#nextbtn").attr("disabled", "disabled");
			
			for(var i = currentWeekDay; i < 7; i++){
		 		$("#tabHeader"+i).attr("style","display:none;");
		 		$("#weektab"+i).remove();
		 	}
	 	} 
	 
	 	$(document).ready(function () {
	 		$('#tabHeader0').addClass('active-nav');
            $('#datepicker').change(function () {
            
               	var date = $('#datepicker').mobiscroll('getDate');
            
	            if(date.getDay()==0){       
	            	startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() - 6);
	            	endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());
	            }
	            else {
	            	startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 1);
	            	endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 7);
	            }
	            
	            var dateFormat = 'yy年mm月dd';

	            $('#startDate').val($.mobiscroll.formatDate(dateFormat, 
	            											startDate, 
	            											$.mobiscroll.i18n.ja.settings) 
	            											+ getdate(startDate.getDay()));
	            $('#endDate').val($.mobiscroll.formatDate(dateFormat, 
	            											endDate, 
	            											$.mobiscroll.i18n.ja.settings) 
	            											+ getdate(endDate.getDay()));
            });
         });
      	
      	function getdate(day){
      		var dayNames = [ "日曜日", "月曜日", "火曜日", "水曜日", "木曜日", "金曜日", "土曜日" ];
      		return dayNames[day];
      	}

	</script>
	<s:include value="/WEB-INF/content/common/footer.jsp" />